package cn.turboinfo.fuyang.api.gateway.admin.controller.consumer;

import cn.turboinfo.fuyang.api.domain.admin.usecase.consumer.ConsumerSearchUseCase;
import cn.turboinfo.fuyang.api.domain.common.service.user.SysUserService;
import cn.turboinfo.fuyang.api.entity.admin.fo.cunsumer.ConsumerFO;
import cn.turboinfo.fuyang.api.entity.common.enumeration.user.UserType;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.QSysUser;
import cn.turboinfo.fuyang.api.entity.common.pojo.user.QUserTypeRel;
import cn.turboinfo.fuyang.api.gateway.admin.fo.consumer.ConsumerSearchFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.ResponseBodyWrapper;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitDataFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.LimitFO;
import cn.turboinfo.fuyang.api.gateway.admin.framework.http.fo.SortFO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.request.QSort;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanSearchHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @author gadzs
 * @description 消费者查询
 * @date 2023/2/17 17:13
 */
@Slf4j
@RequiredArgsConstructor
@Controller
@ResponseBodyWrapper
@RequestMapping("/admin/consumer")
public class ConsumerController {

    private final ConsumerSearchUseCase consumerSearchUseCase;
    private final SysUserService sysUserService;

    @RequiresPermissions("consumer:list")
    @RequestMapping("/list")
    public LimitDataFO<ConsumerFO> list(@Valid ConsumerSearchFO search, LimitFO page, SortFO sort) {
        QRequest request = QBeanSearchHelper.convertQRequest(search);
        if (StringUtils.hasLength(search.getMobile())) {
            val sysUser = sysUserService.getByMobile(search.getMobile()).orElse(null);
            if (Objects.nonNull(sysUser)) {
                request.filterEqual(QUserTypeRel.userId, sysUser.getId());
            }
        }
        request.filterEqual(QUserTypeRel.userType, UserType.Consumer);
        if (sort.getSortFields() == null) {
            sort.setSortFields(new String[]{QSysUser.id + "|" + QSort.Order.DESC.name()});
        }
        ConsumerSearchUseCase.OutputData outputData = consumerSearchUseCase.execute(ConsumerSearchUseCase.InputData
                .builder()
                .request(request)
                .requestPage(page.toQPage(sort.toQSortList()))
                .build());
        return LimitDataFO.fromQResponse(outputData.getQResponse());
    }
}
